package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Address;
import com.itheima.service.AddressService;
import com.itheima.utils.IDutils;
import com.itheima.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.io.IOException;

@RestController
@RequestMapping("/address")
public class AddressController {
    @Reference
    private AddressService addressService;
    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        PageResult pageResult = addressService.PageQusery(queryPageBean);
        return pageResult;
    }

    @RequestMapping("/add")
    public Result add (@RequestBody Address address){
        try {
            addressService.add(address);
        }catch (Exception e){
            e.printStackTrace();
            //服务执行失败
            return new Result(false, MessageConstant.ADD_ADDRESS_SUCCESS);
        }
        return new Result(true,MessageConstant.ADD_ADDRESS_FAILL);
    }

    //文件上传(配置springmvc上传组件)
    @RequestMapping("/upload")
    public Result upload(@RequestParam("imgFile") MultipartFile imgFile) {
        //设置文件名和后缀名
        String originalFilename = imgFile.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        String substring = originalFilename.substring(index);//.jpg
        String fileName = IDutils.getUUId() + substring;

        try {
            //将文件上传到七牛云服务器
            QiniuUtils.upload2Qiniu(imgFile.getBytes(), fileName);
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES, fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.PIC_UPLOAD_SUCCESS);
        } finally {
            if (jedisPool.getResource() != null) {
                //释放资源,资源的回收
                jedisPool.getResource().close();
            }
        }
        return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS, fileName);
    }




//    疯狂加拉加斯的理解
    }


